import { Toast } from "antd-mobile";
import axios from "axios";
import nProgress from "nprogress";
import "nprogress/nprogress.css";
import { getToken, serverUrl } from "./tools";

const instance = axios.create({
  baseURL: serverUrl,
  timeout: 5000,
});

// Add a request interceptor
instance.interceptors.request.use(
  function (config) {
    nProgress.start();
    config.headers["token"] = getToken();
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

// Add a response interceptor
instance.interceptors.response.use(
  function (response) {
    nProgress.done();
    return response.data;
  },
  function (error) {
    // console.log(error);
    const err = error.response;
    Toast.show({ icon: "fail", content: err.status + "   " + err.statusText });
    nProgress.done();
    return Promise.reject(error);
  }
);

export const get = (url, params = {}) => instance.get(url, { params });

export const post = (url, data) => instance.post(url, data);

export const put = (url, data) => instance.put(url, data);

export const patch = (url, data) => instance.patch(url, data);

export const del = (url) => instance.delete(url);
